console.log('进入h01.js');

//document.getElementById: 获取页面对应id的元素
let btn01 = document.getElementById('btn01');
let div01 = document.getElementById('div01');

console.log('页面元素:', btn01, div01);

btn01.addEventListener('click', () => {
  //创建指定类型页面元素<div></div>
  let sp = document.createElement('span');
  //添加内容
  sp.append(new Date().toLocaleDateString());
  //添加到页面指定的元素中
  div01.append(sp);
});

//年月日数据处理
let selNian = document.getElementById('selNian');
let selYue = document.getElementById('selYue');
let selRi = document.getElementById('selRi');

//初始化年份的数据的function
function initNian() {
  let nian = new Date().getFullYear();
  //For(变量初始化；循环是否继续的逻辑表达式；每次循环后执行的代码)
  //三段都不是必须的，但是；是必须

  for (let d = 1970; d <= nian; d++) {
    //创建option元素
    let op = document.createElement('option');
    op.append(d + '年');
    //设置元素的属性
    op.setAttribute('value', d);
    selNian.append(op);
  }
  selNian.value = nian - 20;
}

initNian();

//初始化月份
function initYue() {
  for (let d = 0; d < 13; d++) {
    let op = document.createElement('option');
    op.append(d + '月');
    op.setAttribute('value', d);
    selYue.append(op);
  }
  selYue.value = 6;
}

initYue();

//计算日期信息
function initRi() {
  //通过年月计算日期
  let nian = selNian.value;
  let yue = selYue.value;
  let run = nian % 400 == 0 || (nian % 4 == 0 && 100 != 0);
  console.log('选中的年月:', nian, yue, run);
  //默认为31天
  let ri = 31;
  if (yue == 4 || yue == 6 || yue == 9 || yue == 11) {
    ri = 30;
  } else if (run && yue == 2) {
    ri = 29;
  } else if (yue == 2) {
    ri = 28;
  }
  console.log('天数:', ri);
  //清除掉原有的日期
  selRi.innerHTML = '';
  for (let i = 1; i <= ri; i++) {
    let op = document.createElement('option');
    op.append(i + '日');
    op.setAttribute('value', i);
    selRi.append(op);
  }
  selRi.value = 15;
}

initRi();
//年或者月变化都要触发日期的计算
selNian.addEventListener('change', initRi);
selYue.addEventListener('change', initRi);

//将日期数据格式化成指定内容的字符串
//参数=默认值 表示该参数如果没有传入，就为默认值
function formatDate(date, format = 'yyyy-MM-dd hh:mm:ss') {
  console.log('传入的参数', date, format);
  let now = new Date();
  now = date;
  // 获取年月日时分秒的信息
  let yyyy = now.getFullYear();
  let MM = now.getMonth() + 1;
  let dd = now.getDate();
  let hh = now.getHours();
  let mm = now.getMinutes();
  let ss = now.getSeconds();
  //替换格式字符串成为真正的时间值
  let result = format.replace(/yyyy/g, yyyy);
  result = result.replace(/MM/g, MM);
  result = result.replace(/dd/g, dd);
  result = result.replace(/hh/g, hh);
  result = result.replace(/mm/g, mm);
  result = result.replace(/ss/g, ss);

  return result;
}

let divNow = document.getElementById('divNow');

let date = formatDate(new Date());
console.log('格式化日期信息:', date);
divNow.innerHTML = date;

date = formatDate(new Date(), 'yyyy-MM-dd yyyy年');
console.log('格式化日期信息:', date);

date = formatDate(new Date(), 'hh:mm:ss');
console.log('格式化日期信息:', date);
